#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
K713正确处理脚本
手动解析数据并生成正确的SVG结果
"""

import os
import json
import re
from datetime import datetime
from simple_svg_generator import generate_simple_svg

def parse_k713_manually():
    """手动解析K713数据"""
    print("=== 手动解析K713数据 ===")
    
    filename = "test-data/1KA-ARCH-P-R-K713.txt"
    
    with open(filename, 'r', encoding='utf-8') as f:
        lines = f.readlines()
    
    vertices = []
    current_pos = None
    framework_name = None
    height = None
    
    # 解析状态
    in_ploop = False
    first_vertex_pos = None
    
    for line in lines:
        line = line.strip()
        
        if line.startswith('NEW FRMWORK'):
            framework_name = line.split()[2]
            print(f"框架名称: {framework_name}")
        
        elif line.startswith('NEW PLOOP'):
            in_ploop = True
            print("开始PLOOP")
        
        elif line.startswith('HEIG') and in_ploop:
            height_match = re.search(r'(\d+\.?\d*)mm', line)
            if height_match:
                height = float(height_match.group(1))
                print(f"高度: {height}mm")
        
        elif line.startswith('NEW PAVERT') and in_ploop:
            # 如果有当前位置，添加为顶点
            if current_pos is not None:
                vertices.append(current_pos)
                print(f"添加顶点: {current_pos}")
                if first_vertex_pos is None:
                    first_vertex_pos = current_pos
            current_pos = None
        
        elif line.startswith('POS') and in_ploop:
            # 解析位置 POS W 9100mm N 4600mm U 0mm
            pos_parts = line.split()
            x, y, z = 0, 0, 0
            
            for i in range(1, len(pos_parts), 2):
                if i + 1 < len(pos_parts):
                    direction = pos_parts[i]
                    value_str = pos_parts[i + 1]
                    value = float(re.search(r'(-?\d+\.?\d*)', value_str).group(1))
                    
                    if direction == 'W':
                        x = -value  # W是西，负方向
                    elif direction == 'E':
                        x = value   # E是东，正方向
                    elif direction == 'N':
                        y = value   # N是北，正方向
                    elif direction == 'S':
                        y = -value  # S是南，负方向
                    elif direction == 'U':
                        z = value   # U是上，正方向
            
            current_pos = (x, y, z)
            print(f"解析位置: {line} → ({x}, {y}, {z})")
        
        elif line.startswith('END') and in_ploop and current_pos is None:
            # PLOOP结束，如果还有位置没有添加，添加它
            if current_pos is not None:
                vertices.append(current_pos)
    
    # 移除重复的顶点并清理数据
    print(f"\n原始顶点数: {len(vertices)}")
    
    # 过滤PANEL位置（通常是第一个，坐标很大）
    filtered_vertices = []
    for vertex in vertices:
        # 过滤掉明显是PANEL位置的顶点（坐标绝对值很大）
        if abs(vertex[0]) < 50000 and abs(vertex[1]) < 50000:
            filtered_vertices.append(vertex)
    
    print(f"过滤后顶点数: {len(filtered_vertices)}")
    
    # 移除重复顶点
    unique_vertices = []
    for vertex in filtered_vertices:
        if vertex not in unique_vertices:
            unique_vertices.append(vertex)
    
    print(f"去重后顶点数: {len(unique_vertices)}")
    
    # 确保路径闭合（但不重复添加顶点到数组，让SVG生成器处理）
    if unique_vertices:
        print(f"路径起点: {unique_vertices[0]}")
        print(f"路径终点: {unique_vertices[-1]}")
        if unique_vertices[0] == unique_vertices[-1]:
            print("路径已经闭合")
        else:
            print("路径需要闭合（将在SVG中处理）")
    
    print(f"最终顶点数: {len(unique_vertices)}")
    
    for i, vertex in enumerate(unique_vertices):
        print(f"顶点 {i}: ({vertex[0]:.2f}, {vertex[1]:.2f})")
    
    return {
        'framework_name': framework_name,
        'height': height,
        'vertices': unique_vertices
    }

def calculate_perimeter(vertices):
    """计算周长"""
    if len(vertices) < 2:
        return 0.0
    
    perimeter = 0.0
    for i in range(len(vertices) - 1):
        x1, y1 = vertices[i][:2]
        x2, y2 = vertices[i + 1][:2]
        distance = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
        perimeter += distance
    
    return perimeter

def create_processed_data(parsed_data):
    """创建处理后的数据结构"""
    vertices = parsed_data['vertices']
    
    # 转换为处理器需要的格式
    processed_vertices = []
    for x, y, z in vertices:
        processed_vertices.append({
            'x': x,
            'y': y,
            'z': z,
            'fradius': 0.0
        })
    
    perimeter = calculate_perimeter(vertices)
    
    return {
        'framework_name': parsed_data['framework_name'],
        'height': parsed_data['height'],
        'original_vertices_count': len(vertices),
        'optimized_vertices_count': len(vertices),
        'optimization_rate': 0.0,  # 没有优化
        'total_perimeter': perimeter,
        'fradius_vertices_count': 0,
        'processed_vertices': processed_vertices,
        'fradius_info': []
    }

def main():
    print("=== K713正确处理脚本 ===")
    
    # 输出目录
    output_dir = "results_k713_correct"
    os.makedirs(output_dir, exist_ok=True)
    
    # 手动解析K713
    parsed_data = parse_k713_manually()
    
    if not parsed_data['vertices']:
        print("错误：未能解析出有效顶点")
        return
    
    # 创建处理后的数据
    processed_data = create_processed_data(parsed_data)
    
    # 输出统计信息
    print(f"\n=== 处理统计 ===")
    print(f"框架名称: {processed_data['framework_name']}")
    print(f"高度: {processed_data['height']}mm")
    print(f"顶点数: {processed_data['optimized_vertices_count']}")
    print(f"总周长: {processed_data['total_perimeter']:.2f}mm")
    print(f"FRADIUS顶点: {processed_data['fradius_vertices_count']}")
    
    # 生成简化SVG
    print(f"\n=== 生成简化SVG ===")
    svg_file = os.path.join(output_dir, "k713_correct.svg")
    svg_content = generate_simple_svg(
        processed_data, 
        processed_data['framework_name']
    )
    
    with open(svg_file, 'w', encoding='utf-8') as f:
        f.write(svg_content)
    
    print(f"正确SVG已生成: {svg_file}")
    
    # 生成处理报告
    report_file = os.path.join(output_dir, "k713_correct_report.json")
    report = {
        'framework_name': processed_data['framework_name'],
        'processing_time': datetime.now().isoformat(),
        'input_file': "test-data/1KA-ARCH-P-R-K713.txt",
        'vertices_count': processed_data['optimized_vertices_count'],
        'total_perimeter': processed_data['total_perimeter'],
        'height': processed_data['height'],
        'processed_vertices': processed_data['processed_vertices'],
        'notes': "手动解析K713数据，正确处理顶点坐标"
    }
    
    with open(report_file, 'w', encoding='utf-8') as f:
        json.dump(report, f, ensure_ascii=False, indent=2)
    
    print(f"处理报告已生成: {report_file}")
    
    print(f"\n=== K713正确处理完成 ===")

if __name__ == "__main__":
    main() 